package com.ylxin.smartplatform.service.impl;

import com.sun.xml.internal.bind.v2.TODO;
import com.ylxin.smartplatform.constans.ResultCode;
import com.ylxin.smartplatform.exceptions.AddDataException;
import com.ylxin.smartplatform.mapper.DeviceMapper;
import com.ylxin.smartplatform.pojo.SysDevice;
import com.ylxin.smartplatform.pojo.SysUserInfo;
import com.ylxin.smartplatform.service.DeviceService;
import com.ylxin.smartplatform.service.SceneService;
import com.ylxin.smartplatform.utils.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.xml.transform.Result;

/**
 * @author 29048
 * @version V1.0
 * @Project bk2205
 * @Package com.ylxin.smartplatform.service.impl
 * @Description: Create by 杨立新 @Date 2022/9/15 21:58
 */
@Component
@Repository
@Service
@Transactional
public class DeviceServiceImpl implements DeviceService {

    private SceneService sceneService;

    private DeviceService deviceService;

    //绑定设备要用
    private DeviceMapper deviceMapper;

    public void setSceneService(SceneService sceneService) {
        this.sceneService = sceneService;
    }

    public void setDeviceService(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    @Override
    public void addDevice(SysDevice sysDevice) {
        //我们需要获取当前需要的用户
        SysUserInfo userInfo = SecurityUtils.getLoginUser();
        sysDevice.setBindUserId(userInfo.getUId());

        //TODO 判断分类是不是存在

        //如果传递了场景id，我们还得判断当前的这个场景id属于这个用户
        Long sceneId = sysDevice.getSceneId();
        if(sceneId != null && (-1 > sceneId || 0 == sceneId)){
            //传递了id 但是id 不符合要求，
            throw new AddDataException("场景不存在", ResultCode.DATA_NOT_EXIST);
        }else if(sceneId != null && 0 < sceneId){
            //传递了一个场景id 但这个场景不一定属于谁
            //判断是否输入当前用户
            sceneService.getSceneById(sceneId);
        }

        //这个设备可能已经绑定到了其他的人身上
        SysDevice device = findByDeviceId(sysDevice.getDeviceId());
        //如果设备已经绑定到了其他人身上我们就不能绑定了
        Assert.isTrue(device == null || device.getBindUserId().equals(sysDevice.getBindUserId()),() -> {
            throw new AddDataException("设备已经被绑定", ResultCode.DATA_ALREADY_EXIST);
        });

        if(device == null){
            //执行绑定操作
            deviceMapper.bindDevice(sysDevice);
        }
    }

    @Override
    public SysDevice findByDeviceId(String id) {
        return deviceMapper.findByDeviceId(id);
    }

    @Override
    public int updateDeviceStatus(String deviceId, int status) {
        return 0;
    }

    @Override
    public void sendCommand(String deviceId, String command) {

    }
}
